<script setup>
import {nextTick, reactive, ref} from 'vue'
import useSystemStore from '@/stores/system'
import pinia from '@/stores/store'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
const dialogVisible=ref(false)

// 相机拍照

const videoWidth = ref(730);

const videoHeight = ref(400);

const imgSrc = ref("");

const blobFile = ref(null);

const thisCancas = ref(null);

const thisContext = ref(null);

const thisVideo = ref(null);

const emit = defineEmits(["refreshDataList"]);

//   vue中使用摄像头拍照(监听摄像头)
const handleDiglog=()=>{
    dialogVisible.value=true
    nextTick(()=>{
        getCompetence()
    })
}
const handleClose=()=>{

    dialogVisible.value=false

    nextTick(()=>{
        stopNavigator()

    })
}

const getCompetence=()=> {

    thisCancas.value = document.getElementById("canvasCamera");

    thisContext.value = thisCancas.value.getContext("2d");

    thisVideo.value = document.getElementById("videoCamera");

    // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象

    if (navigator.mediaDevices === undefined) {

        navigator.mediaDevices = {};

    }

    // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象

    // 使用getUserMedia，因为它会覆盖现有的属性。

    // 这里，如果缺少getUserMedia属性，就添加它。

    if (navigator.mediaDevices.getUserMedia === undefined) {

        navigator.mediaDevices.getUserMedia = function (constraints) {

            // 首先获取现存的getUserMedia(如果存在)

            let getUserMedia =

                navigator.webkitGetUserMedia ||

                navigator.mozGetUserMedia ||

                navigator.getUserMedia;

            // 有些浏览器不支持，会返回错误信息

            // 保持接口一致

            if (!getUserMedia) {

                return Promise.reject(

                    new Error("getUserMedia is not implemented in this browser")

                );

            }

            // 否则，使用Promise将调用包装到旧的navigator.getUserMedia

            return new Promise(function (resolve, reject) {

                getUserMedia.call(navigator, constraints, resolve, reject);

            });

        };

    }

    let constraints = {

        audio: false,

        video: {

            width: videoWidth.value,

            height: videoHeight.value,

            transform: "scaleX(-1)",

        },

    };

    navigator.mediaDevices

        .getUserMedia(constraints)

        .then(function (stream) {


            if ("srcObject" in thisVideo.value) {

                thisVideo.value.srcObject = stream;

            } else {



                thisVideo.value.src = window.URL.createObjectURL(stream);

            }

            thisVideo.value.onloadedmetadata = function (e) {

                thisVideo.value.play();

            };

        })

        .catch((err) => {

            console.log(err);

        });

}
const setImage = async () => {



    thisContext.value.drawImage(

        thisVideo.value,

        0,

        0,

        videoWidth.value,

        videoHeight.value

    );


    let image = thisCancas.value.toDataURL("image/png");

    console.log(dataURLtoFile(image, "图片文件")); // 转换为file文件

    blobFile.value = dataURLtoFile(image, "图片文件");

    let formData = new FormData();

    formData.append("file", blobFile.value,"filename.jpg"); //图片内容


    console.log(formData.getAll("file")[0], "查看数据内容", formData); // 查看数据内容

    imgSrc.value = image;

    emit("refreshDataList", imgSrc.value);

    // console.log("图片数据", imgSrc.value) ;

    //这是我的接口啊！你可得写你自己得后端接口

    const res = await request.post(

        "http://localhost:9090/api/file/upload",
        formData
    );
    userInfo.userPhoto=res.data
    dialogVisible.value=false
    nextTick(()=>{
        stopNavigator()

    })

};

// base64转文件

function dataURLtoFile(dataurl, filename) {

    let arr = dataurl.split(",");

    let mime = arr[0].match(/:(.*?);/)[1];

    let bstr = atob(arr[1]);

    let n = bstr.length;

    let u8arr = new Uint8Array(n);

    while (n--) {

        u8arr[n] = bstr.charCodeAt(n);

    }

    return new File([u8arr], filename, { type: mime });

}

// 关闭摄像头

const stopNavigator=()=> {

    thisVideo.value.srcObject.getTracks()[0].stop();

}
const systemStore = useSystemStore(pinia)
const userInfo = systemStore.userInfo

const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = reactive(userInfo)

const rules = reactive({
    nickname: [
        { required: true, message: '输入用户昵称', trigger: 'blur' },
        { min: 2, max: 5, message: '长度在2到5位之间', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        {
            pattern: /^1[3456789]\d{9}$/,
            message: '手机号格式不正确',
            trigger: 'blur'
        }
    ],
    email: [
        { required: true, message: '请输入邮箱号', trigger: 'blur' },
        {
            type: 'email',
            message: '邮箱地址格式不正确',
            trigger: ['blur']
        }
    ],
    content: [
        { required: true, message: '请输个人简介', trigger: 'blur' },
        { min: 5, max: 100, message: '长度在5到100位之间', trigger: 'blur' }
    ]
})

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            await request.put('/user', ruleForm)
            ElMessage({
                showClose: true,
                message: '操作成功',
                type: 'success'
            })
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`
}))
// 上传成功以后
const handleAvatarSuccess = async (file) => {
    let fd = new FormData()
    fd.append('file', file)
    const res = await request.post('/file/upload', fd, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    })
    ElMessage({
        showClose: true,
        message: '上传成功',
        type: 'success'
    })
    ruleForm.avatar = res.data
    ruleFormRef.value.clearValidate('avatar')
    nextTick(()=>{
        stopNavigator()
    })
}
</script>
<script>
export default {
    name: 'Info'
}
</script>
<template>
    <el-dialog :model-value="dialogVisible" title="请正对摄像头" :before-close="handleClose">

        <!-- poster="背景图" -->

        <video

                id="videoCamera"
                width="710"
                height="400"
                autoplay

        />

        <canvas

                style="display: none;margin: 0 auto"
                id="canvasCamera"
                :width="710"
                :height="400"

        ></canvas>

        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button @click="setImage" type="primary">确认</el-button>
      </span>
        </template>
    </el-dialog>
    <el-row>
        <el-col :sm="8">
            <el-form
                    ref="ruleFormRef"
                    :model="ruleForm"
                    :rules="rules"
                    label-width="80px"
                    class="demo-ruleForm"
                    :size="formSize"
                    status-icon
            >
                <el-form-item label="人脸照片" prop="avatar">

                    <img v-if="ruleForm.userPhoto" :src="ruleForm.userPhoto" class="avatar" @click="handleDiglog" />
                    <el-icon v-else class="avatar-uploader-icon" @click="handleDiglog"><Plus /></el-icon>

                </el-form-item>
                <el-form-item label="用户头像" prop="avatar">
                    <el-upload
                            class="avatar-uploader"
                            :show-file-list="false"
                            :before-upload="handleAvatarSuccess"
                    >
                        <el-avatar :size="30" v-if="ruleForm.avatar" :src="ruleForm.avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="账户名称" prop="username">
                    <el-input v-model="ruleForm.username" disabled />
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickname">
                    <el-input v-model="ruleForm.nickname" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="ruleForm.phone" />
                </el-form-item>
                <el-form-item label="个人邮箱" prop="email">
                    <el-input v-model="ruleForm.email" />
                </el-form-item>
                <el-form-item label="个人简介" prop="content">
                    <el-input v-model="ruleForm.content" type="textarea" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)"> 确认修改 </el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<style scoped lang="scss">

.avatar {
  width: 178px;
  height: 118px;
  display: block;
}
</style>
